<?php

namespace app\controller;
use app\BaseController;
use app\model\EnterpriseMember;
use app\model\User;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Member extends BaseController
{
    public function index(Request $request): Json
    {
        $payload = $request->get();
        //校验是否存在 user_id,enterprise_id，并且不能为空
        if (empty($payload['user_id']) || empty($payload['enterprise_id'])) {
            return $this->result(400, '参数错误');
        }
        //从 enterprise_member表中查询enterprise_id所有用户，并获取用户信息
        $memberModel = new EnterpriseMember();
        $data = [];
        try {
            $result = $memberModel->where('enterprise_id', $payload['enterprise_id'])
                ->with(['userinfo', 'role'])
                ->select();
            foreach ($result as $item){
                $data[] = [
                    'user_id' => $item->user_id,
                    'role_id' => $item->role_id,
                    'role_name' => $item->role->role_name,
                    'role_style'=> $item->role->style,
                    'user_name' => $item->userinfo->username,
                    'user_avatar' => $item->userinfo->user_avatar,
                    'user_mobile' => $item->userinfo->mobile,
                    'join_time' => $item->join_time,
                    'enterprise_id' => $item->enterprise_id
                ];
            }
            return $this->result(200, '查询成功', $data);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
}